#include "openglItem.h"

#define timeOutmSec 500
#define AHEAD_TIME  200

OpenGLItem::OpenGLItem()
    : m_render(0)
{
    //m_timer.start(12, this);
    connect(this, &QQuickItem::windowChanged, this, [this](QQuickWindow *window)
    {
        if (window)
        {
            connect(window, &QQuickWindow::beforeSynchronizing, this, &OpenGLItem::sync,
                    Qt::DirectConnection);
            connect(window, &QQuickWindow::sceneGraphInvalidated, this, &OpenGLItem::cleanup,
                    Qt::DirectConnection);
        }
    });
#if 0
    connect(&m_timer,&QTimer::timeout,this,&OpenGLItem::on_timeOut);
    m_timer.start(timeOutmSec);
    //    m_timer.setSingleShot(true);


    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &OpenGLItem::goAhead);
    timer->start(AHEAD_TIME);
#endif
}

OpenGLItem::~OpenGLItem()
{

}

void OpenGLItem::sync()
{
    if (!m_render)
    {
        m_render = new Render();
        m_render->initializeGL();
        m_render->resizeGL(window()->width(), window()->height()/2);
        connect(window(), &QQuickWindow::beforeRendering, this, [this]()
            {
                m_render->render();
                //渲染qml前不清画面，保留opengl
                window()->setClearBeforeRendering(false);
            }, Qt::DirectConnection);
        connect(window(), &QQuickWindow::afterRendering, this, [this]()
            {
                //渲染后调用，计算fps
            }, Qt::DirectConnection);
        connect(window(), &QQuickWindow::widthChanged, this, [this]()
                {

                    m_render->resizeGL(window()->width(), window()->height());
                });
        connect(window(), &QQuickWindow::heightChanged, this, [this]()
                {

                    m_render->resizeGL(window()->width(), window()->height());
                });

        connect(m_render, &Render::sigUpdate, this, [&]
                {
            window()->update();
         });


    }
}

void OpenGLItem::cleanup()
{
    if (m_render)
    {
        delete m_render;
        m_render = nullptr;
    }
}
#if 0
void OpenGLItem::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event);
    window()->update();
}
#endif

void OpenGLItem::on_timeOut()
{
    if(m_render)
    {
        m_render->on_timeOut();
        window()->update();
    }
}

void OpenGLItem::goAhead()
{
    if(m_render)
    {
        m_render->goAhead();
        window()->update();
    }
}
